<?php
/**
 * 系统设置模型
 *
 * @copyright   Copyright 2011, Richie
 * @author      Richie <richbossman@163.com>
 * @package     SMS
 * @link        http://www.letphp.com
 * 
 * $Id: SetModel.class.php 52 2011-03-24 15:00:25Z 442767452@qq.com $
 */
class SetModel extends SMSModel {
	//
	protected $_validate	=	array(
		array('var','checkName', '变量名称已经存在！',0,'callback'),
	);
	//自动完成
	protected $_auto = array(
		array('add_time', 'time', 1, 'function'),
	);
	
	//检查应用名称是否存在
	function checkName(){
		$map['var']	 =	 $_POST['var'];
        if(!empty($_POST['id'])) {
			$map['id']	=	array('neq',$_POST['id']);
        }
		$result	=	$this->where($map)->field('id')->find();
        if($result) {
        	return false;
        }else{
			return true;
		}
	}
	
	//取得配置组
	function getGroup(){
		return $this->where("type='group'")->order('sort ASC, id DESC')->getField('id,name');
	}
	
	//所有列表
	function getSetList(){
		$group = $this->getGroup();
		$groups = array();
		foreach($group as $id=>$name){
			$groups[$id]['text'] = $name;
			$groups[$id]['group'] = $this->getChildrenList($id);
		}
		return $groups;
	}
	
	//子列表
	function getChildrenList($pid){
		$children = $this->where('parent_id='.$pid." AND type<>'hidden'")->order('sort ASC, id DESC')->findAll();
		if($children){
			foreach($children as $key=>$child){
				$children[$key]['value_list'] = $this->compileValue($child['value_list']);
			}
		}
		return $children;
	}
	
	//编译值列表
	function compileValue($value=''){
		if(empty($value)) return array();
		$vals = array();
		$val = explode(',', $value);
		foreach($val as $key=>$v){
			$vl = explode('|', $v);
			if($vl){
				$vals[$key]['text'] = isset($vl[0]) ? $vl[0] : '';
				$vals[$key]['value'] = isset($vl[1]) ? $vl[1] : '';
			}
		}
		return $vals;
	}
	
	//更新配置
	function updateSet($sets){
		foreach($sets as $key=>$value){
			$this->where('id='.$key)->save(array("value"=>$value));
		}
	}
}
?>